package com.myaihui.controller;

import com.belonk.msoffice.excel.util.POIExcelUtil;
import com.myaihui.domain.PMBill;
import com.myaihui.domain.SysUser;
import com.myaihui.foundation.constant.SysConst;
import com.myaihui.foundation.model.Pager;
import com.myaihui.foundation.msg.MsgDefinition;
import com.myaihui.foundation.msg.ResultMsg;
import com.myaihui.foundation.query.PMBillQuery;
import com.myaihui.service.PMBillItemService;
import com.myaihui.service.PMBillService;
import com.myaihui.util.LoginUtil;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.shiro.util.Assert;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.*;

/**
 * Created by sun on 2018/9/8.
 *
 * @author sunfuchang03@126.com
 * @version 1.0
 * @since 1.0
 */
@Controller
@RequestMapping("/pmbill/needpay")
public class PMNeedPayBillController {
    /*
     * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
     *
     * Static fields/constants/initializer
     *
     * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
     */

    private static Logger log = LoggerFactory.getLogger(PMNeedPayBillController.class);

    /*
     * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
     *
     * Instance fields
     *
     * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
     */

    @Autowired
    private PMBillService pmBillService;
    @Autowired
    private PMBillItemService pmBillItemService;

    /*
     * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
     *
     * Constructors
     *
     * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
     */



    /*
     * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
     *
     * Public Methods
     *
     * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
     */

    @GetMapping({"/", ""})
    public String home(Model model) {
        return "pmneedpaybill/home";
    }

    @GetMapping("/detail/{id}")
    public String detail(@PathVariable String id, Model model) {
        PMBill bill = pmBillService.getById(id);
        model.addAttribute("bill", bill);
        return "pmneedpaybill/detail";
    }

    @PostMapping("/page")
    @ResponseBody
    public ResultMsg queryPageData(PMBillQuery query) {
        SysUser sysUser = LoginUtil.loginUser();
        if (sysUser.getPlatformType() != SysConst.SubjectType.PROPERTY) {
            return ResultMsg.error("403", "Unauthorized");
        }
        query.setStatus(SysConst.PMBillState.NEED_PAY);
        query.setPropertyMgrId(sysUser.getPlatformId());
        Pager<PMBill> contentPager = pmBillService.pageQuery(query);
        return ResultMsg.success(contentPager);
    }

    @RequestMapping("/save")
    @ResponseBody
    public ResultMsg save(PMBill bill) {
        String id = bill.getId();
        SysUser sysUser = LoginUtil.loginUser();
        if (StringUtils.hasLength(id)) {
            PMBill src = pmBillService.getById(id);
            src.setHouseNumber(bill.getHouseNumber());
            src.setUserName(bill.getUserName());
            src.setUserMobile(bill.getUserMobile());
            src.setDuration(bill.getDuration());
            src.setTotalAmount(bill.getTotalAmount());
            src.setReleaseTime(bill.getReleaseTime());
            src.setRemark(bill.getRemark());
            src.setLastModifiedTime(new Date());
            src.setLastModifiedUserId(sysUser.getId());
            bill = pmBillService.update(src);
        } else {
            bill.setCreateUserId(sysUser.getId());
            bill.setCreateUserPlatformId(sysUser.getPlatformId());
            bill.setCreateUserPlatformType(SysConst.SubjectType.PROPERTY);
            bill = pmBillService.add(bill);
        }
        return ResultMsg.success(bill);
    }

    @PostMapping("/del")
    @ResponseBody
    public ResultMsg batchDelete(String ids) {
        if (!StringUtils.hasLength(ids)) {
            return ResultMsg.error(MsgDefinition.EMPTY_ARGUMENTS);
        }
        String[] idArray = ids.split(",");
        for (String id : idArray) {
            pmBillService.delete(id);
        }
        return ResultMsg.success(true);
    }

    @PostMapping("/delete/{id}")
    @ResponseBody
    public ResultMsg delete(@PathVariable String id) {
        if (!StringUtils.hasLength(id)) {
            return ResultMsg.error(MsgDefinition.EMPTY_ARGUMENTS);
        }
        pmBillService.delete(id);
        return ResultMsg.success(true);
    }

    @PostMapping("/publish/{id}")
    @ResponseBody
    public ResultMsg publish(@PathVariable String id) {
        if (!StringUtils.hasLength(id)) {
            return ResultMsg.error(MsgDefinition.EMPTY_ARGUMENTS);
        }
        PMBill bill = pmBillService.getById(id);
        bill.setPublished(true);
        bill.setPublishTime(new Date());
        pmBillService.update(bill);
        // TODO 模板消息和短信通知
        return ResultMsg.success(true);
    }

    @PostMapping("/import")
    @ResponseBody
    public ResultMsg importBill(@RequestParam("billExcel") MultipartFile excel) {
        Assert.notNull(excel);
        try {
            Workbook workbook = POIExcelUtil.createWorkbook(excel.getInputStream());
            // 获取第一个sheet
            Sheet sheet = workbook.getSheetAt(0);
            Map<String, Object> result = pmBillService.importFromExcel(sheet);
            List<Integer> errorRows = (List<Integer>) result.get("errorRows");
            Map<String, Object> rtn = new HashMap<>();
            if (errorRows != null) {
                Collections.reverse(errorRows);
                rtn.put("hasError", true);
                rtn.put("failedRowCnt", errorRows.size());
                rtn.put("failedRowNumber", errorRows);
            }
            return ResultMsg.success(rtn);
        } catch (IOException e) {
            log.error("Create workbook error : ", e);
            return ResultMsg.error(MsgDefinition.UNKOWN_ERROR);
        }
    }

    /*
     * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
     *
     * Private Methods
     *
     * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
     */


}